#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cron: 0 8 * * *
# const $ = new Env("综合营收汇总报告");
import os
import re
import glob
import time
from datetime import datetime
from wechat_test import wechat_sender

# 日志目录配置
LOG_DIR = "/ql/data/log/Message/"

# 日志解析器配置
LOG_PARSERS = [
    {
        "name": "新江北",
        "file_pattern": "PUSH_xjb.log",
        "patterns": {
            "total_accounts": re.compile(r"👥 总账号数: (\d+)个"),
            "exchange_success": re.compile(r"✅ 兑换成功金额: ([\d.]+)元"),
            "failed_accounts": re.compile(r"⚠️ 兑换失败账号数: (\d+)个"),
            "exchange_failed": re.compile(r"❌ 兑换失败金额: ([\d.]+)元")
        },
        "revenue_key": "exchange_success"
    },
    {
        "name": "康师傅",
        "file_pattern": "PUSH_ksfpg.log",
        "patterns": {
            "total_accounts": re.compile(r"👥 总账号数: (\d+)个"),
            "total_profit": re.compile(r"🏆 总利润: ([\d.]+)元"),
            "waste_codes": re.compile(r"❌ 总废码量: (\d+)个")
        },
        "revenue_key": "total_profit"
    },
    {
        "name": "甬派",
        "file_pattern": "PUSH_yp.log",
        "patterns": {
            "total_accounts": re.compile(r"• 总账号数: (\d+)"),
            "exchange_success": re.compile(r"• 本次总获: ([\d.]+)元"),
            "historical_total": re.compile(r"• 历史累计: ([\d.]+)元"),
            "failed_accounts": re.compile(r"• 失败账号: (\d+)")
        },
        "revenue_key": "exchange_success"
    },
    {
        "name": "大潮",
        "file_pattern": "PUSH_dachao.log",
        "patterns": {
            "total_accounts": re.compile(r"用户总数: (\d+)"),
            "revenue": re.compile(r"总金额: ([\d.]+)元"),
            "redpacket_count": re.compile(r"红包总数: (\d+)个?")
        },
        "revenue_key": "revenue"
    },
    {
        "name": "快手",
        "file_pattern": "PUSH_kuaishou.log",
        "patterns": {
            "total_accounts": re.compile(r"👤 总账号数: (\d+)个"),
            "total_cash": re.compile(r"💵 总现金余额: ([\d.]+)元"),
            "today_withdraw": re.compile(r"💸 今日提现金额: ([\d.]+)元"),
            "duck_eggs": re.compile(r"🥚 鸭蛋总数: (\d+)个"),
            "gold_coins": re.compile(r"💰 总金币量: (\d+)金币")
        },
        "revenue_key": "today_withdraw",
        "special_parse": "kuaishou"
    },
    {
        "name": "in嘉善",
        "file_pattern": "PUSH_in嘉善.log",
        "patterns": {
            "total_accounts": re.compile(r"总账号数: (\d+)个"),
            "revenue": re.compile(r"红包总金额: ([\d.]+)元"),
            "failed_attempts": re.compile(r"未中奖次数: (\d+)次")
        },
        "revenue_key": "revenue"
    },
    {
        "name": "星芽短剧",
        "file_pattern": "PUSH_XYDJ.log",
        "special_parse": "xingya"
    }
]

def parse_xingya_data(content):
    """专门解析星芽短剧数据，精确匹配有备注的账号"""
    noted_accounts = set()
    total_cash = 0.0
    today_withdraw = 0.0
    withdrawable_accounts = []
    
    account_blocks = re.finditer(
        r"🔷 账号\d+ \[(\d+) - (.*?)\](?:[\s\S]*?)"
        r"💰 当前金币: \d+(?:[\s\S]*?)"
        r"💵 现金余额: ([\d.]+)元(?:[\s\S]*?)"
        r"💸 今日提现: ([\d.]+)元",
        content
    )
    
    for match in account_blocks:
        account_id = match.group(1)
        remark = match.group(2).strip()
        cash = float(match.group(3))
        withdraw = float(match.group(4))
        
        if remark and remark != "无备注":
            noted_accounts.add(account_id)
            total_cash += cash
            today_withdraw += withdraw
            if cash >= 15.0:
                withdrawable_accounts.append(remark)
    
    return {
        "total_accounts": str(len(noted_accounts)),
        "total_cash": f"{total_cash:.2f}",
        "today_withdraw": f"{today_withdraw:.2f}",
        "withdrawable_accounts": withdrawable_accounts,
        "withdrawable_accounts_str": "、".join(withdrawable_accounts) if withdrawable_accounts else "无",
        "revenue": f"{today_withdraw:.2f}"
    }

def parse_kuaishou_data(content):
    """专门解析快手数据"""
    withdrawable_accounts = []
    account_blocks = re.finditer(
        r"🔷 \[(.*?)\][\s\S]*?"
        r"💵 现金余额: ([\d.]+)元[\s\S]*?"
        r"💸 今日提现: ([\d.]+)元",
        content
    )
    
    for match in account_blocks:
        account_name = match.group(1).strip()
        cash = float(match.group(2))
        if cash >= 15.0:
            withdrawable_accounts.append(account_name)
    
    return {
        "withdrawable_accounts": withdrawable_accounts,
        "withdrawable_accounts_str": "、".join(withdrawable_accounts) if withdrawable_accounts else "无"
    }

def parse_yp_failures(content):
    """解析甬派日志中的失败次数"""
    failure_count = 0
    account_lines = re.findall(r"✅ 账号\d+: .*失败", content)
    for line in account_lines:
        failure_count += line.count("失败")
    return str(failure_count)

def parse_injiashan_failures(content):
    """解析in嘉善日志中的失败账号数"""
    failure_accounts = set()
    account_lines = re.findall(r"🔷 (\d+).*?(❌\d+次)", content)
    for account, failure in account_lines:
        failure_accounts.add(account)
    return str(len(failure_accounts))

def parse_log_file(file_path, parser_config):
    """解析单个日志文件并提取关键信息"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        if parser_config.get("special_parse") == "xingya":
            return parse_xingya_data(content)
        elif parser_config.get("special_parse") == "kuaishou":
            results = {}
            for key, pattern in parser_config["patterns"].items():
                match = pattern.search(content)
                results[key] = match.group(1) if match else "0"
            kuaishou_data = parse_kuaishou_data(content)
            results.update(kuaishou_data)
            return results
        
        results = {}
        for key, pattern in parser_config["patterns"].items():
            match = pattern.search(content)
            results[key] = match.group(1) if match else "0"
        
        if parser_config["name"] == "甬派":
            results["total_failures"] = parse_yp_failures(content)
        if parser_config["name"] == "in嘉善":
            results["failed_accounts"] = parse_injiashan_failures(content)
        
        if "revenue_key" in parser_config:
            revenue_key = parser_config["revenue_key"]
            if revenue_key in results:
                results["revenue"] = results[revenue_key]
        
        return results
    except Exception as e:
        print(f"⚠️ 解析日志 {file_path} 失败: {str(e)}")
        return {}

def generate_summary_report(report_data):
    """生成汇总报告"""
    total_revenue = 0
    for item in report_data:
        if "revenue" in item and item["revenue"]:
            try:
                total_revenue += float(item["revenue"])
            except:
                pass
    
    report = "📊 昨日综合营收汇总报告\n"
    for i, item in enumerate(report_data, 1):
        name = item["name"]
        revenue = item.get("revenue", "0")
        
        if name == "新江北":
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"✅营收{revenue}元 "
                   f"⚠️失败{item.get('failed_accounts', '0')}个 "
                   f"❌失败{item.get('exchange_failed', '0')}元")
        elif name == "康师傅":
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"✅营收{revenue}元 "
                   f"⚠️废码{item.get('waste_codes', '0')}个")
        elif name == "甬派":
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"✅营收{revenue}元 "
                   f"⚠️失败{item.get('total_failures', '0')}次 "
                   f"💰累计{item.get('historical_total', '0')}元")
        elif name == "大潮":
            redpacket_count = item.get('redpacket_count', '0')
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"✅营收{revenue}元 "
                   f"🧧红包{redpacket_count}个")
        elif name == "快手":
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"💵现金{item.get('total_cash', '0')}元 "
                   f"💸提现{revenue}元 "
                   f"🏅可提现【{item.get('withdrawable_accounts_str', '无')}】 "
                   f"🥚鸭蛋{item.get('duck_eggs', '0')}个")
        elif name == "in嘉善":
            failed_accounts = item.get('failed_accounts', '0')
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"✅营收{revenue}元 "
                   f"❌失败{failed_accounts}个")
        elif name == "星芽短剧":
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', '0')}个 "
                   f"💵现金{item.get('total_cash', '0')}元 "
                   f"💸提现{revenue}元 "
                   f"🏅可提现【{item.get('withdrawable_accounts_str', '无')}】")
        else:
            line = (f"{i}️⃣{name}：👥总账号{item.get('total_accounts', 'N/A')}个 "
                   f"✅营收{revenue}元")
        
        report += line + "\n"
    
    report += f"💰 当日营收合计【{total_revenue:.2f}】元\n"
    report += f"📅 报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    return report

def send_wechat_notification(message, receiver_id=None):
    """发送企业微信通知"""
    if not receiver_id:
        receiver_id = os.environ.get("SUMMARY_RECEIVER")
        if not receiver_id:
            print("❌ 未配置汇总报告接收人ID")
            return False
    
    print(f"📤 发送汇总报告给接收人 {receiver_id}...")
    success = wechat_sender.send_message(receiver_id, message)
    if success:
        print("✅ 汇总报告发送成功")
    else:
        print("❌ 汇总报告发送失败")
    return success

def main():
    print("="*50)
    print("综合营收汇总报告生成脚本启动")
    print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    report_data = []
    for parser_config in LOG_PARSERS:
        print(f"\n🔍 处理 {parser_config['name']} 日志...")
        log_files = glob.glob(os.path.join(LOG_DIR, parser_config["file_pattern"]))
        
        if not log_files:
            print(f"⚠️ 未找到 {parser_config['name']} 日志文件")
            empty_item = {"name": parser_config["name"]}
            
            if parser_config.get("special_parse") == "xingya":
                empty_item.update({
                    "total_accounts": "0",
                    "total_cash": "0",
                    "today_withdraw": "0",
                    "withdrawable_accounts_str": "无",
                    "revenue": "0"
                })
            elif parser_config.get("special_parse") == "kuaishou":
                empty_item.update({
                    "total_accounts": "0",
                    "total_cash": "0",
                    "today_withdraw": "0",
                    "duck_eggs": "0",
                    "withdrawable_accounts_str": "无",
                    "revenue": "0"
                })
            else:
                for key in parser_config.get("patterns", {}).keys():
                    empty_item[key] = "0"
                if parser_config["name"] == "in嘉善":
                    empty_item["failed_accounts"] = "0"
            
            if "revenue_key" in parser_config:
                revenue_key = parser_config["revenue_key"]
                empty_item["revenue"] = empty_item.get(revenue_key, "0")
            
            report_data.append(empty_item)
            continue
        
        log_file = log_files[0]
        print(f"📄 找到日志文件: {log_file}")
        log_data = parse_log_file(log_file, parser_config)
        
        if not log_data:
            print(f"⚠️ 未从 {parser_config['name']} 日志中提取到数据")
            log_data = {"name": parser_config["name"]}
            
            if parser_config.get("special_parse") == "xingya":
                log_data.update({
                    "total_accounts": "0",
                    "total_cash": "0",
                    "today_withdraw": "0",
                    "withdrawable_accounts_str": "无",
                    "revenue": "0"
                })
            elif parser_config.get("special_parse") == "kuaishou":
                log_data.update({
                    "total_accounts": "0",
                    "total_cash": "0",
                    "today_withdraw": "0",
                    "duck_eggs": "0",
                    "withdrawable_accounts_str": "无",
                    "revenue": "0"
                })
            else:
                for key in parser_config.get("patterns", {}).keys():
                    log_data[key] = "0"
                if parser_config["name"] == "in嘉善":
                    log_data["failed_accounts"] = "0"
        
        if "revenue" not in log_data and "revenue_key" in parser_config:
            revenue_key = parser_config["revenue_key"]
            log_data["revenue"] = log_data.get(revenue_key, "0")
        
        if parser_config["name"] == "in嘉善" and "failed_accounts" not in log_data:
            log_data["failed_accounts"] = "0"
        
        if parser_config.get("special_parse") == "xingya":
            if "withdrawable_accounts_str" not in log_data:
                log_data["withdrawable_accounts_str"] = "无"
            if "revenue" not in log_data:
                log_data["revenue"] = log_data.get("today_withdraw", "0")
        
        if parser_config.get("special_parse") == "kuaishou":
            if "withdrawable_accounts_str" not in log_data:
                log_data["withdrawable_accounts_str"] = "无"
            if "revenue" not in log_data:
                log_data["revenue"] = log_data.get("today_withdraw", "0")
        
        log_data["name"] = parser_config["name"]
        report_data.append(log_data)
        print(f"📋 提取数据: {log_data}")
    
    summary_report = generate_summary_report(report_data)
    print("\n📝 生成的汇总报告:")
    print(summary_report)
    
    send_success = send_wechat_notification(summary_report)
    print(f"\n{'✅ 完成!' if send_success else '❌ 部分操作失败'}")
    print("="*50)

if __name__ == "__main__":
    main()